<template>
    <div class="admin-container">
      <h1>管理员管理</h1>
  
      <!-- 搜索框和新增按钮区域 -->
      <div class="search-container" style="margin-bottom: 20px; display: flex; gap: 10px; align-items: center;">
        <el-input
          v-model="searchKeyword"  
          placeholder="请输入账号或备注关键词搜索" 
          style="width: 510px;"  
          clearable 
          @keyup.enter="handleSearch"  
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="success" @click="showAddDialog">新增管理员</el-button>
      </div>
  
      <!-- 管理员表格：编辑按钮保留 -->
      <el-table 
        :data="adminsList"  
        style="width: 100%; margin: 20px auto; border: 1px solid #eee;"
        border
        stripe
        :loading="tableLoading" 
      >
        <el-table-column prop="aid" label="管理员ID" width="160" align="center" />
        <el-table-column prop="acount" label="管理员账号" width="300" align="center" />
        <el-table-column prop="apcid" label="PCID" width="200" align="center" />
        <el-table-column prop="aremarks" label="备注" width="300" align="center" />
        <el-table-column prop="permissionId" label="权限ID" width="160" align="center" />
        <el-table-column label="操作" width="320" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showAdminDetail(scope.row)" style="margin-right: 8px;">查看详情</el-button>
            <!-- 编辑按钮：直接传递当前行数据 -->
            <el-button type="warning" size="small" icon="Edit" @click="showUpdateDialog(scope.row)" style="margin-right: 8px;">编辑</el-button>
            <el-button type="danger" size="small" icon="Delete" @click="handleDelete(scope.row.aid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页功能 -->
      <div style="text-align: center; margin: 20px 0;">
        <el-pagination
          :page-size="params.pageSize"
          :total="params.recordCount"
          v-model:current-page="params.pageNum"
          @current-change="queryAdmins"
          layout="total,prev,pager,next"
          :disabled="tableLoading"
        />
      </div>
  
      <!-- 详情弹窗（保留） -->
      <el-dialog title="管理员详情" v-model="detailVisible" width="50%" :close-on-click-modal="false">
        <el-descriptions column="1" border>
          <el-descriptions-item label="管理员ID">{{ currentAdmin.aid || '-' }}</el-descriptions-item>
          <el-descriptions-item label="管理员账号">{{ currentAdmin.acount || '-' }}</el-descriptions-item>
          <el-descriptions-item label="PCID">{{ currentAdmin.apcid || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ currentAdmin.aremarks || '-' }}</el-descriptions-item>
          <el-descriptions-item label="权限ID">{{ currentAdmin.permissionId || '-' }}</el-descriptions-item>
        </el-descriptions>
      </el-dialog>
  
      <!-- 删除弹窗（保留） -->
      <el-dialog title="删除确认" v-model="deleteVisible" width="30%" :close-on-click-modal="false">
        <div>确定要删除 ID 为 <span style="color: #f56c6c; font-weight: 500;">{{ deleteAid }}</span> 的管理员吗？删除后不可恢复！</div>
        <template #footer>
          <el-button @click="deleteVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete" :loading="deleteLoading">确认删除</el-button>
        </template>
      </el-dialog>

      <!-- 新增弹窗（保留核心验证） -->
      <el-dialog title="新增管理员" v-model="addVisible" width="50%" :close-on-click-modal="false">
        <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="120px" style="margin-top: 20px;">
          <el-form-item label="管理员账号" prop="acount">
            <el-input v-model="addForm.acount" placeholder="请输入管理员账号" />
          </el-form-item>
          <el-form-item label="管理员密码" prop="apwd">
            <el-input v-model="addForm.apwd" placeholder="请输入管理员密码" type="password" />
          </el-form-item>
          <el-form-item label="权限ID" prop="permissionId">
            <el-input v-model.number="addForm.permissionId" placeholder="请输入权限ID" type="number" />
          </el-form-item>
          <!-- 非核心字段（PCID、备注）去掉验证，可选填 -->
          <el-form-item label="PCID">
            <el-input v-model="addForm.apcid" placeholder="可选：请输入PCID" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="addForm.aremarks" placeholder="可选：请输入备注信息" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="confirmAdd" :loading="addLoading">确认添加</el-button>
        </template>
      </el-dialog>

      <!-- 更新弹窗：简化验证，直接用当前行aid -->
      <el-dialog title="编辑管理员" v-model="updateVisible" width="50%" :close-on-click-modal="false">
        <el-form ref="updateFormRef" :model="updateForm" :rules="updateFormRules" label-width="120px" style="margin-top: 20px;">
          <!-- 隐藏aid：直接用表格行的aid，不允许修改 -->
          <el-form-item v-show="false" prop="aid">
            <el-input v-model="updateForm.aid" />
          </el-form-item>
          <!-- 核心字段保留基础验证，非核心字段无验证 -->
          <el-form-item label="管理员账号" prop="acount">
            <el-input v-model="updateForm.acount" placeholder="请输入管理员账号" />
          </el-form-item>
          <el-form-item label="权限ID" prop="permissionId">
            <el-input v-model.number="updateForm.permissionId" placeholder="请输入权限ID" type="number" />
          </el-form-item>
          <!-- 非核心字段：无验证，密码不填则不更新 -->
          <el-form-item label="管理员密码">
            <el-input v-model="updateForm.apwd" placeholder="不填则保持原密码" type="password" />
          </el-form-item>
          <el-form-item label="PCID">
            <el-input v-model="updateForm.apcid" placeholder="可选：请输入PCID" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="updateForm.aremarks" placeholder="可选：请输入备注信息" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="cancelUpdate">取消</el-button>
          <el-button type="primary" @click="confirmUpdate" :loading="updateLoading">确认更新</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  <script setup>
  import { ref, reactive } from 'vue';
  import { Edit, Delete } from '@element-plus/icons-vue';
  import { ElMessage } from 'element-plus';
  
  // 导入接口（保留核心）
  import { queryPage, deleteById, updateById } from '@/api/admin';
  import { insertSave } from '@/api/admin';
  
  // 1. 基础参数（无修改）
  const searchKeyword = ref("");
  const params = ref({ pageNum: 1, pageSize: 5, recordCount: 0 });
  
  // 2. 页面状态：简化变量，保留核心
  const adminsList = ref([]);
  const [detailVisible, deleteVisible, addVisible, updateVisible] = [ref(false), ref(false), ref(false), ref(false)];
  const currentAdmin = ref({});
  const deleteAid = ref('');
  const [tableLoading, deleteLoading, addLoading, updateLoading] = [ref(false), ref(false), ref(false), ref(false)];
  
  // 3. 表单引用（保留核心）
  const addFormRef = ref();
  const updateFormRef = ref();
  
  // 4. 表单数据：简化结构，非核心字段可选
  const addForm = reactive({ acount: '', apwd: '', apcid: '', aremarks: '', permissionId: null });
  const updateForm = reactive({ aid: null, acount: '', apwd: '', apcid: '', aremarks: '', permissionId: null });
  
  // 5. 验证规则：大幅简化，只保留核心必填项
  const addFormRules = reactive({
    acount: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
    apwd: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
    permissionId: [{ required: true, message: '权限ID不能为空', trigger: 'blur' }, { type: 'number', message: '权限ID需为数字', trigger: 'blur' }]
  });
  const updateFormRules = reactive({
    // 只验证核心字段：aid（隐藏必传）、acount、permissionId
    acount: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
    permissionId: [{ required: true, message: '权限ID不能为空', trigger: 'blur' }, { type: 'number', message: '权限ID需为数字', trigger: 'blur' }]
  });
  
  // 6. 核心查询逻辑（无修改）
  function queryAdmins() {
    tableLoading.value = true;
    queryPage(searchKeyword.value.trim(), searchKeyword.value.trim(), params.value.pageNum, params.value.pageSize)
      .then(data => {
        adminsList.value = data.list || [];
        params.value.recordCount = data.pager?.recordCount || 0;
      })
      .catch(() => { ElMessage.error('加载失败'); adminsList.value = []; })
      .finally(() => tableLoading.value = false);
  }
  
  // 7. 搜索/重置/详情/删除（无修改，保留核心）
  function handleSearch() { params.value.pageNum = 1; queryAdmins(); }
  function handleReset() { searchKeyword.value = ""; params.value.pageNum = 1; queryAdmins(); }
  function showAdminDetail(admin) { currentAdmin.value = admin; detailVisible.value = true; }
  function handleDelete(aid) { if (aid && typeof aid === 'number') { deleteAid.value = aid; deleteVisible.value = true; } else ElMessage.warning('无效ID'); }
  function confirmDelete() {
    deleteLoading.value = true;
    deleteById(deleteAid.value)
      .then(() => { ElMessage.success(`删除成功`); deleteVisible.value = false; queryAdmins(); })
      .catch(() => ElMessage.error('删除失败'))
      .finally(() => deleteLoading.value = false);
  }
  
  // 8. 新增功能：简化非核心字段验证（无逻辑修改）
  function showAddDialog() { addFormRef.value?.resetFields(); addVisible.value = true; }
  function cancelAdd() { addVisible.value = false; addFormRef.value?.resetFields(); }
  function confirmAdd() {
    addFormRef.value?.validate(valid => {
      if (valid) {
        addLoading.value = true;
        insertSave(addForm)
          .then(() => { ElMessage.success('新增成功'); addVisible.value = false; queryAdmins(); })
          .catch(() => ElMessage.error('新增失败'))
          .finally(() => addLoading.value = false);
      }
    });
  }
  
  // 9. 更新功能：核心优化！直接用当前行aid，简化赋值
  function showUpdateDialog(admin) {
    // 直接赋值当前行数据（无需深拷贝，因aid隐藏且不修改，其他字段修改不影响表格原始数据）
    updateForm.aid = admin.aid; // 强制赋值aid，确保定位正确
    updateForm.acount = admin.acount;
    updateForm.apcid = admin.apcid || '';
    updateForm.aremarks = admin.aremarks || '';
    updateForm.permissionId = admin.permissionId;
    updateForm.apwd = ''; // 密码默认清空，不填则不更新
    updateFormRef.value?.clearValidate(); // 清除之前的验证状态
    updateVisible.value = true;
  }
  function cancelUpdate() { updateVisible.value = false; updateFormRef.value?.resetFields(); }
  function confirmUpdate() {
    updateFormRef.value?.validate(valid => {
      if (valid) {
        updateLoading.value = true;
        // 直接传递带aid的updateForm，接口通过aid定位更新
        updateById(updateForm)
          .then(() => { ElMessage.success(`更新成功`); updateVisible.value = false; queryAdmins(); })
          .catch(() => ElMessage.error('更新失败'))
          .finally(() => updateLoading.value = false);
      }
    });
  }
  
  // 初始化查询
  queryAdmins();
  </script>